
import React from 'react';
import { Form, Select, TreeSelect, Radio, InputNumber, Checkbox } from 'antd';
import { Drawer, Tabs, Space, Button } from 'antd';
import _ from 'lodash'

import TimeDeltaPicker from './TimeDeltaPicker'
import MeasurementTree from './MeasurementTree'

import intl from '../intl'
import { TableType, DataType } from '../core/common'
import { TimeFillHoder, SeqFillHoder, StatFillHoder, StatTimeFillHoder, FillHepler } from '../core/fill'
import { DayUtil } from '../util/utils'

const OPTION_PORTRAIT = [
  { value: true, label: '纵向', },
  { value: false, label: '横向', },
];


class FillSeqChooser extends React.Component {
  constructor(props) {
    super(props);

    this.onValuesChange = this.onValuesChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.onFinish = this.onFinish.bind(this);
    this.onFinishFailed = this.onFinishFailed.bind(this);
    this.onTabChange = this.onTabChange.bind(this);

    this.form1Ref = React.createRef();
    this.form2Ref = React.createRef();

    const tableTypeOptions = TableType.optionsForSeq();
    this.state = {
      activeKey: '1',
      tableType: tableTypeOptions[0].value,
      tableTypeOptions,
    };
  }

  onTabChange(activeKey) {
    this.setState({ activeKey });
  }

  handleSubmit() {
    this.form1Ref.current.submit();
  }
  onFinish(values) {
    const values2 = this.form2Ref.current.getFieldsValue();
    values = Object.assign(values, values2);
    console.log('Success:', values);
    const { measurement, portrait } = values;
    /**
     * measurement:
[{
"point_id": "ANALOG:256:r220:ai:0",
"point_desc": "[思源SVG水冷型]接入点PCC电压AB相",
"point_type": 127
}, ...]
     */
    let stats = values.stats || [];
    const helper = new FillHepler(window.luckysheet, this.props.config.book_type, portrait);

    measurement.forEach((point, index) => {
      if (index === 0) {
        // 添加Time holder
        const timeHoder = new TimeFillHoder({ ...values, id: point.point_id });
        helper.setCellValue(1, 0, timeHoder);
      }

      // 添加列名
      helper.setCellValue(0, 1 + index, point.point_desc);
      // 添加Seq holder
      const seqHolder = new SeqFillHoder({ ...values, id: point.point_id });
      helper.setCellValue(1, 1 + index, seqHolder);

      let row = 2;
      for (const s of stats) {
        const dataType = DataType.getByValue(s);
        if (index === 0) {
          // 添加统计名称
          const colTitle = dataType.colTitle || dataType.label;
          helper.setCellValue(row, 0, colTitle);
          if (dataType.hasTime) {
            helper.setCellValue(row + 1, 0, colTitle + '发生时间');
          }
        }

        // 添加Stat holder
        const props = { ...values, id: point.point_id, data_type: s };
        const statHolder = new StatFillHoder(props);
        helper.setCellValue(row++, 1 + index, statHolder);
        if (dataType.hasTime) {
          const statTimeHolder = new StatTimeFillHoder(props);
          helper.setCellValue(row++, 1 + index, statTimeHolder);
        }
      }
    });

    this.props.onComplete();
  };
  onFinishFailed(errorInfo) {
    console.log('Failed:', errorInfo);
    this.setState({ activeKey: '1' });
  };

  onValuesChange(changedValues, allValues) {
    console.log('onValuesChange', changedValues, allValues);
    if ('table_type' in changedValues) {
      this.setState({ tableType: changedValues.table_type });
    }
  };

  render() {
    const { config, open, onCancel } = this.props;
    const state = this.state;
    const dataTypeOptions = DataType.optionsForSeq(config.book_type);
    const statTreeData = DataType.treeDataForStat(config.book_type);
    const default_elta_desc = DayUtil.formatTimeDelta(config.begin_delta) + ' - ' + DayUtil.formatTimeDelta(config.end_delta);
    const initialValues = {
      table_type: state.tableType,
      data_type: !_.isEmpty(dataTypeOptions) && dataTypeOptions[0].value,
      portrait: true,
      zero: config.zero,
    };
    let diffUnit = '';
    if (config.book_type === 'DAY') {
      diffUnit = '天';
    } else if (config.book_type === 'WEEK') {
      diffUnit = '周';
    } else if (config.book_type === 'MONTH') {
      diffUnit = '月';
    } else if (config.book_type === 'YEAR') {
      diffUnit = '年';
    }

    const form1 = (
      <Form
        colon={false}
        labelCol={{ span: 4, }}
        wrapperCol={{ span: 20, }}
        ref={this.form1Ref}
        initialValues={initialValues}
        onValuesChange={this.onValuesChange}
        onFinish={this.onFinish}
        onFinishFailed={this.onFinishFailed}>

        <Form.Item
          label="库类型"
          name="table_type">
          {/* <Select options={tableTypeOptions} /> */}
          <Radio.Group optionType="button" buttonStyle="solid"
            options={state.tableTypeOptions} />
        </Form.Item>
        <Form.Item
          label="测量点"
          name="measurement"
          rules={[
            {
              required: true,
              message: '请选择测量点!',
            },
          ]}>
          {/* <Transfer
                        showSearch
                        dataSource={state.measurements}
                        render={(item) => item.title}
                    /> */}
          <MeasurementTree tableType={state.tableType} />
        </Form.Item>

        <Form.Item
          label="数据类型"
          name="data_type">
          <Select options={dataTypeOptions} />
        </Form.Item>
        <Form.Item
          label="统计值"
          name="stats">
          {/* <Select mode="multiple" options={statTypeOptions} /> */}
          <TreeSelect
            showSearch
            allowClear
            multiple
            treeDefaultExpandAll
            treeData={statTreeData}
          />
        </Form.Item>
      </Form>
    )

    const form2 = (
      <Form
        colon={false}
        labelCol={{ span: 4, }}
        wrapperCol={{ span: 20, }}
        ref={this.form2Ref}
        initialValues={initialValues}>

        <Form.Item
          label={intl.messages.label_zero}
          tooltip={intl.messages.tooltip_zero}
          name="zero"
          valuePropName="checked">
          <Checkbox />
        </Form.Item>
        <Form.Item
          label={intl.messages.label_ratio}
          tooltip={intl.messages.tooltip_ratio}
          name="ratio">
          <InputNumber placeholder='1' />
        </Form.Item>
        <Form.Item
          label={intl.messages.label_portrait}
          tooltip={intl.messages.tooltip_portrait}
          name="portrait">
          <Radio.Group optionType="button" buttonStyle="solid"
            options={OPTION_PORTRAIT} />
        </Form.Item>

        <Form.Item
          label={intl.messages.label_diff}
          tooltip={intl.messages.tooltip_diff}
          name="diff">
          <InputNumber addonAfter={diffUnit}
            min={-31} max={31} placeholder='0' />
        </Form.Item>

        <Form.Item
          label={intl.messages.label_delta_time}
          tooltip={intl.messages.tooltip_delta_time}
          extra={`默认偏移${default_elta_desc}`}>
          <Form.Item
            name="begin_delta"
            style={{
              display: 'inline-block',
              marginBottom: 0,
            }}>
            {/* <TimePicker format="HH:mm" placeholder="开始时间" /> */}
            <TimeDeltaPicker placeholder="开始时间" />
          </Form.Item>
          <span style={{
            display: 'inline-block',
            width: '24px',
            lineHeight: '32px',
            textAlign: 'center',
          }} > - </span>
          <Form.Item
            name="end_delta"
            style={{
              display: 'inline-block',
              marginBottom: 0,
            }}>
            {/* <TimePicker format="HH:mm" placeholder="结束时间" /> */}
            <TimeDeltaPicker placeholder="结束时间" />
          </Form.Item>
        </Form.Item>
      </Form>
    )

    const items = [
      {
        key: '1',
        label: `数据源`,
        children: form1,
        forceRender: true,
      },
      {
        key: '2',
        label: `配置信息`,
        children: form2,
        forceRender: true,
      }
    ];

    return (
      <Drawer title="序列填充"
        width={550}
        zIndex={1020}
        bodyStyle={{ paddingTop: 0 }}
        open={open}
        onClose={onCancel}
        extra={
          <Space>
            <Button onClick={onCancel}>取消</Button>
            <Button onClick={this.handleSubmit} type="primary">
              确定
            </Button>
          </Space>
        }>
        <Tabs activeKey={state.activeKey} items={items} onChange={this.onTabChange} />
      </Drawer>
    )
  }
}

export default FillSeqChooser